<template>
  <view class="add-account-page">
    <!-- 导航栏 -->
    <tn-nav-bar
      fixed
      backgroundColor="#020303"
      :isBack="true"
      fontColor="#FFFFFF">
      <view class="nav-title">
        {{ pageTitle }}
      </view>
    </tn-nav-bar>

    <view class="container" :style="{paddingTop: vuex_status_bar_height + 44 + 30 + 'px'}">
      <!-- 重新提交模式的说明 -->
      <view class="mode-notice" v-if="mode === 'resubmit'">
        <view class="notice-header">
          <text class="tn-icon-warning"></text>
          <text class="notice-title">重新提交审核</text>
        </view>
        <view class="notice-content">
          <text>您的游戏昵称过于复杂，系统识别失败。</text>
          <text>请修改相关信息后重新提交审核。</text>
        </view>
      </view>

      <view class="form-box">
        <!-- 账号区服选择 -->
        <view class="form-item">
          <view class="form-label">
            <text>选择区服</text>
            <text class="required">*</text>
          </view>
          <view class="server-selector">
            <view
              class="server-option"
              :class="{'active': serverType === 'wechat', 'disabled': mode === 'edit'}"
              @tap="mode !== 'edit' ? selectServer('wechat') : null"
            >
              <text class="tn-icon-weixin-fill"></text>
              <text>微信区</text>
            </view>
            <view
              class="server-option"
              :class="{'active': serverType === 'qq', 'disabled': mode === 'edit'}"
              @tap="mode !== 'edit' ? selectServer('qq') : null"
            >
              <text class="tn-icon-QQ-fill"></text>
              <text>QQ区</text>
            </view>
          </view>
        </view>

        <!-- 游戏ID -->
        <view class="form-item">
          <view class="form-label">
            <text>游戏ID</text>
            <text class="required">*</text>
          </view>
          <view class="input-wrapper">
            <input
              class="contact-input"
              type="text"
              v-model="gameId"
              placeholder="请输入游戏ID"
              :disabled="mode === 'edit'"
            />
          </view>
        </view>

        <!-- 段位选择 -->
        <view class="form-item">
          <view class="form-label">
            <text>游戏段位</text>
            <text class="required">*</text>
          </view>
          <view class="input-wrapper rank-selector" @tap="showRankSelect = true">
            <view class="picker-value" :class="{'placeholder': rankIndex === -1}">
              {{ rankIndex === -1 ? '请选择段位' : rankOptions[rankIndex].label }}
            </view>
            <text class="tn-icon-arrow-down"></text>
          </view>
        </view>

        <!-- 联系方式 -->
        <view class="form-item" v-if="shouldShowContactField">
          <view class="form-label">
            <text>{{serverType === 'wechat' ? '微信号' : 'QQ号'}}</text>
            <text class="required">*</text>
          </view>
          <view class="input-wrapper">
            <input
              class="contact-input"
              type="text"
              v-model="contactNumber"
              :placeholder="serverType === 'wechat' ? '请输入微信号' : '请输入QQ号'"
              @input="validateContactNumber"
            />
          </view>
          <view class="input-tip" v-if="contactTip">
            <text class="tn-icon-info"></text>
            <text>{{contactTip}}</text>
          </view>
          <!-- 增加固定的提示信息，只在用户未输入内容时显示 -->
          <view class="warning-tip" v-if="!contactNumber">
            <text class="tn-icon-warning"></text>
            <text>{{serverType === 'wechat' ? '请务必填写正确微信号，否则将无法联系！wxid_开头的微信号无法被搜索到，建议使用普通微信号。' : '请务必填写正确QQ号，否则将无法联系！'}}</text>
          </view>
        </view>

        <!-- 游戏截图上传 -->
        <view class="form-item upload-item">
          <view class="form-label">
            <text>游戏主页截图</text>
            <text class="required">*</text>
            <text class="tip">（需要审核通过后才可使用账号）</text>
          </view>
          <view class="upload-area" @tap="mode !== 'edit' ? uploadScreenshot() : null">
            <template v-if="!screenshotUrl">
              <view class="upload-btn" :class="{'disabled': mode === 'edit'}">
                <text class="tn-icon-add"></text>
                <text>{{ mode !== 'edit' ? '点击上传截图' : '暂无截图' }}</text>
              </view>
            </template>
            <template v-else>
              <image class="screenshot-preview" :src="screenshotUrl" mode="aspectFit"></image>
              <view class="delete-btn" @tap.stop="mode !== 'edit' ? deleteScreenshot() : null" v-if="mode !== 'edit'">
                <text class="tn-icon-close"></text>
              </view>
              <!-- 上传进度条 -->
              <view class="upload-progress-container" v-if="isUploading && uploadProgress < 100">
                <view class="upload-progress-bar" :style="{width: uploadProgress + '%'}"></view>
                <view class="upload-progress-text">{{ uploadProgress }}%</view>
              </view>
            </template>
          </view>
          <view class="upload-tips">
            请上传游戏个人主页截图，包含游戏ID和段位信息，用于验证账号真实性。
          </view>
        </view>

        <!-- 参考图 -->
        <view class="form-item reference-item">
          <view class="form-label">
            <text>参考图示例</text>
          </view>
          <view class="reference-images">
            <image
              src="https://rbtnet.oss-cn-hangzhou.aliyuncs.com/c856298deb718e1ad67080bc6acb6b7e1c169f61d1e46c1a20d8dbe6e3a0edcc.jpg"
              mode="aspectFit"
              class="reference-image"
              @tap="previewReferenceImage"
            ></image>
          </view>
          <view class="reference-tip">
            参考上方图片，请截取包含您游戏ID和段位信息的游戏个人主页
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @tap="submitAccount" :disabled="!canSubmit">{{ submitButtonText }}</button>
    </view>

    <!-- 段位选择器 -->
    <tn-select
      v-model="showRankSelect"
      mode="single"
      :list="rankOptions"
      :defaultValue="[0]"
      valueName="value"
      labelName="label"
      title="选择段位"
      cancelColor="#888888"
      confirmColor="#B3F73C"
      titleColor="#FFFFFF"
      @confirm="onRankConfirm"
      @cancel="showRankSelect = false"
      ref="rankSelect"
    >
      <template v-slot:header>
        <view class="custom-select-header">
          <view class="header-cancel" @tap="showRankSelect = false">取消</view>
          <view class="header-title">选择段位</view>
          <view class="header-confirm" @tap="$refs.rankSelect.getResult('confirm')">确定</view>
        </view>
      </template>
    </tn-select>

    <!-- 审核等待弹窗 -->
    <view v-if="showAuditDialog" class="audit-modal-overlay" @tap.stop="">
      <view class="audit-modal" @tap.stop="">
        <!-- 王者荣耀风格背景 -->
        <view class="audit-modal-bg">
          <!-- 顶部装饰 -->
          <view class="audit-header">
            <view class="audit-title">账号审核中</view>
            <view class="audit-subtitle">正在验证账号信息</view>
          </view>

          <!-- 中间动画区域 -->
          <view class="audit-animation">
            <!-- 旋转的王者荣耀风格圆环 -->
            <view class="audit-ring">
              <view class="ring-outer" :class="{ 'success': auditStatus === 1, 'failed': auditStatus === 2 }"></view>
              <view class="ring-inner" :class="{ 'success': auditStatus === 1, 'failed': auditStatus === 2 }"></view>
              <view class="ring-center" :class="{ 'success': auditStatus === 1, 'failed': auditStatus === 2 }">
                <!-- 等待状态：王者荣耀图标 -->
                <view v-if="auditStatus === 0" class="waiting-icon">⚔️</view>
                <!-- 成功状态：勾号特效 -->
                <view v-else-if="auditStatus === 1" class="success-icon">✓</view>
                <!-- 失败状态：叉号特效 -->
                <view v-else-if="auditStatus === 2" class="failed-icon">✗</view>
              </view>
            </view>

            <!-- 状态文字 -->
            <view class="audit-status" :class="{ 'success': auditStatus === 1, 'failed': auditStatus === 2 }">
              {{ auditMessage }}
            </view>

            <!-- 进度条 -->
            <view class="audit-progress">
              <view class="progress-bar">
                <view class="progress-fill"
                      :class="{ 'success': auditStatus === 1, 'failed': auditStatus === 2 }"
                      :style="{ width: auditProgressWidth + '%' }">
                </view>
              </view>
            </view>
          </view>

          <!-- 底部按钮 -->
          <view class="audit-footer" v-if="auditStatus === 2">
            <button class="audit-btn" @tap="closeAuditModal">我知道了</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加VIP弹窗组件 -->
    <vip-popup
      :show.sync="isVipModalVisible"
      :userInfo="userInfo"
      @purchase-success="onVipPurchaseSuccess"
    ></vip-popup>
  </view>
</template>

<script>
import api from '@/api/index.js';
import { getAllRanks } from '@/utils/constants.js';
import config from '@/config/index.js';
import VipPopup from '@/components/vip/vip-popup.vue';
import { mapState, mapGetters } from 'vuex';
import { uploadFile } from '@/api/upload/index.js';

export default {
  components: {
    VipPopup
  },
  data() {
    return {
      // 页面模式相关
      mode: 'add', // 页面模式：add-添加，edit-编辑，resubmit-重新提交
      accountId: null, // 编辑或重新提交时的账号ID
      originalAccountData: null, // 原始账号数据（用于编辑模式）

      screenshotUrl: '', // 本地预览图片URL
      serverScreenshotUrl: '', // 上传到服务器后的URL
      uploadProgress: 0, // 上传进度
      isUploading: false, // 是否正在上传
      serverType: 'wechat', // 默认选择微信区
      contactNumber: '', // 联系方式（微信号或QQ号）
      contactTip: '', // 联系方式提示信息
      gameId: '', // 游戏ID
      rankIndex: -1, // 初始未选择状态为-1
      rankOptions: getAllRanks().map(rank => ({
        label: rank.name,
        value: rank.id
      })),
      showRankSelect: false, // 控制段位选择器显示

      // 审核弹窗相关
      showAuditDialog: false, // 控制审核弹窗显示
      auditAccountId: null, // 当前审核的账号ID
      auditCountdown: 30, // 倒计时秒数
      auditTimer: null, // 倒计时定时器
      auditCheckTimer: null, // 查询状态定时器
      auditStatus: 0, // 审核状态：0待审核 1通过 2拒绝
      auditMessage: '正在验证账号信息...', // 审核提示信息
      auditProgress: 0, // 审核进度 0-100

      // VIP弹窗控制变量
      isVipModalVisible: false,
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    }),
    // 从config模块获取wxAuditMode
    ...mapGetters('config', ['wxAuditMode']),

    vuex_status_bar_height() {
      return uni.getSystemInfoSync().statusBarHeight || 0;
    },

    // 页面标题
    pageTitle() {
      switch(this.mode) {
        case 'edit': return '编辑游戏账号';
        case 'resubmit': return '重新提交审核';
        default: return '添加游戏账号';
      }
    },

    // 提交按钮文字
    submitButtonText() {
      switch(this.mode) {
        case 'edit': return '保存修改';
        case 'resubmit': return '重新提交审核';
        default: return '提交审核';
      }
    },

    // 是否显示联系方式字段
    shouldShowContactField() {
      // 开启微信审核模式时，微信号和QQ号都不显示
      if (this.wxAuditMode) {
        return false;
      }
      // 其他情况都显示
      return true;
    },

    canSubmit() {
      // 编辑模式需要联系方式和段位
      if (this.mode === 'edit') {
        // 如果不显示联系方式字段，则不需要验证联系方式
        if (!this.shouldShowContactField) {
          return this.rankIndex !== -1;
        }
        return this.contactNumber && !this.contactTip && this.rankIndex !== -1;
      }
      // 添加和重新提交模式需要完整信息
      if (!this.shouldShowContactField) {
        // 如果不显示联系方式字段，则不需要验证联系方式
        return this.screenshotUrl && this.serverScreenshotUrl && this.gameId && this.rankIndex !== -1;
      }
      return this.screenshotUrl && this.contactNumber && !this.contactTip && this.serverScreenshotUrl && this.gameId && this.rankIndex !== -1;
    },

    // 审核进度条宽度
    auditProgressWidth() {
      if (this.auditStatus === 1) {
        return 100; // 成功时进度条满格
      } else if (this.auditStatus === 2) {
        return 100; // 失败时进度条也满格，但颜色不同
      } else {
        return this.auditProgress; // 审核中时显示实际进度
      }
    }
  },

  // 页面加载时处理参数
  onLoad(options) {
    console.log('页面参数:', options);

    // 获取页面参数
    if (options.id) {
      this.accountId = parseInt(options.id);
    }
    if (options.mode) {
      this.mode = options.mode;
    }

    // 如果是编辑或重新提交模式，加载账号数据
    if ((this.mode === 'edit' || this.mode === 'resubmit') && this.accountId) {
      this.loadAccountData();
    }
  },

  methods: {
    // 加载账号数据（编辑和重新提交模式）
    async loadAccountData() {
      try {
        uni.showLoading({
          title: '加载中...'
        });

        const accountData = await api.game.getGameKingAccount(this.accountId);
        if (!accountData) {
          throw new Error('账号不存在');
        }

        // 保存原始数据
        this.originalAccountData = accountData;
        console.log('加载的账号数据:', accountData);

        // 填充表单数据
        this.gameId = accountData.gameId || '';
        this.serverType = accountData.areaType === 1 ? 'wechat' : 'qq';
        this.contactNumber = accountData.contact || '';

        // 设置段位
        if (accountData.rankLevel) {
          const rankIndex = this.rankOptions.findIndex(rank => rank.value === accountData.rankLevel);
          this.rankIndex = rankIndex !== -1 ? rankIndex : -1;
          console.log('段位设置:', accountData.rankLevel, '索引:', this.rankIndex);
        }

        // 设置截图（如果有）
        if (accountData.screenshot) {
          this.screenshotUrl = accountData.screenshot;
          this.serverScreenshotUrl = accountData.screenshot;
          console.log('截图设置:', accountData.screenshot);
        }

        console.log('表单数据回显完成:', {
          gameId: this.gameId,
          serverType: this.serverType,
          contactNumber: this.contactNumber,
          rankIndex: this.rankIndex,
          screenshotUrl: this.screenshotUrl
        });

        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        console.error('加载账号数据失败:', error);
        uni.showToast({
          title: '加载账号数据失败',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },

    // 选择区服
    selectServer(type) {
      this.serverType = type;
      // 切换区服时重新验证联系方式
      this.validateContactNumber();
    },

    // 段位选择确认
    onRankConfirm(e) {
      console.log('段位选择确认:', e);
      // 基于控制台输出，e是一个数组，直接检查第一个元素
      if (Array.isArray(e) && e.length > 0) {
        // 找到匹配的选项索引
        const selectedValue = e[0].value;
        for (let i = 0; i < this.rankOptions.length; i++) {
          if (this.rankOptions[i].value === selectedValue) {
            this.rankIndex = i;
            break;
          }
        }
      }
      this.showRankSelect = false;
    },

    // 自定义确认按钮点击事件
    onRankSelectConfirm() {
      // 直接调用组件的确认方法
      this.$refs.rankSelect.getResult('confirm');
    },

    // 验证联系方式
    validateContactNumber() {
      // 清空提示
      this.contactTip = '';

      // 检查是否为空
      if (!this.contactNumber) {
        return;
      }

      if (this.serverType === 'wechat') {
        // 微信号验证
        if (this.contactNumber.startsWith('wxid_')) {
          this.contactTip = '注意：以wxid_开头的微信号无法被搜索到，请使用普通微信号以便他人联系';
        } else if (!/^[a-zA-Z][\w-]{5,19}$/.test(this.contactNumber)) {
          this.contactTip = '微信号格式不正确，请输入正确的微信号，否则将无法被联系';
        }
      } else {
        // QQ号验证
        if (!/^\d{5,12}$/.test(this.contactNumber)) {
          this.contactTip = 'QQ号格式不正确，请输入5-12位数字的QQ号，否则将无法被联系';
        }
      }
    },

    // 上传截图
    uploadScreenshot() {
      if (this.isUploading) {
        uni.showToast({
          title: '图片上传中，请稍候',
          icon: 'none'
        });
        return;
      }

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.screenshotUrl = tempFilePath;
          this.uploadProgress = 0;
          this.isUploading = true;

          // 使用统一的上传文件API上传图片
          uploadFile({
            filePath: tempFilePath,
            fileType: 'game/account', // 游戏账号相关的图片
            onProgress: (progress) => {
              // 更新上传进度
              this.uploadProgress = progress;
            }
          }).then(imageUrl => {
            // 上传成功后，保存服务器返回的URL
            this.serverScreenshotUrl = imageUrl;
            this.uploadProgress = 100;
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          }).catch(err => {
            console.error('上传截图失败:', err);
            uni.showToast({
              title: err.message || '图片上传失败，请重试',
              icon: 'none'
            });
            // 上传失败时清除预览图片
            this.screenshotUrl = '';
            this.serverScreenshotUrl = '';
          }).finally(() => {
            this.isUploading = false;
            this.uploadProgress = 0;
          });
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 删除截图
    deleteScreenshot() {
      if (this.isUploading) {
        uni.showToast({
          title: '图片上传中，无法删除',
          icon: 'none'
        });
        return;
      }

      this.screenshotUrl = '';
      this.serverScreenshotUrl = '';
      this.uploadProgress = 0;
    },

    // 预览参考图
    previewReferenceImage() {
      uni.previewImage({
        urls: ['https://rbtnet.oss-cn-hangzhou.aliyuncs.com/c856298deb718e1ad67080bc6acb6b7e1c169f61d1e46c1a20d8dbe6e3a0edcc.jpg'],
        current: 0
      });
    },

    // 提交账号
    submitAccount() {
      // 根据模式执行不同的提交逻辑
      switch(this.mode) {
        case 'resubmit':
          this.handleResubmit();
          break;
        case 'edit':
          this.handleEdit();
          break;
        default:
          this.handleCreate();
          break;
      }
    },

    // 处理重新提交审核
    async handleResubmit() {
      // 检查游戏ID是否填写
      if (!this.gameId) {
        uni.showToast({
          title: '请填写游戏ID',
          icon: 'none'
        });
        return;
      }

      // 检查是否选择了段位
      if (this.rankIndex === -1) {
        uni.showToast({
          title: '请选择段位',
          icon: 'none'
        });
        return;
      }

      // 检查联系方式是否填写（仅在显示联系方式字段时验证）
      if (this.shouldShowContactField) {
        if (!this.contactNumber) {
          if (this.serverType === 'wechat') {
            this.contactTip = '请填写微信号以便联系';
          } else {
            this.contactTip = '请填写QQ号以便联系';
          }
          return;
        }

        // 再次验证联系方式
        this.validateContactNumber();

        // 如果有错误提示，不提交
        if (this.contactTip) {
          uni.showToast({
            title: '请检查输入信息',
            icon: 'none'
          });
          return;
        }
      }

      // 检查截图是否上传
      if (!this.screenshotUrl) {
        uni.showToast({
          title: '请上传游戏主页截图',
          icon: 'none'
        });
        return;
      }

      // 检查是否正在上传图片
      if (this.isUploading) {
        uni.showToast({
          title: '图片上传中，请稍后提交',
          icon: 'none'
        });
        return;
      }

      // 检查图片是否已上传到服务器
      if (!this.serverScreenshotUrl) {
        uni.showToast({
          title: '请先上传游戏主页截图',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({
          title: '重新提交中...'
        });

        // 调用重新校验接口
        await api.game.retryVerifyGameAccount(this.accountId);

        uni.hideLoading();

        // 显示审核等待弹窗（与新增模式相同）
        this.showAuditModal(this.accountId);

      } catch (error) {
        uni.hideLoading();
        console.error('重新提交审核失败:', error);

        // 检查是否是需要开通会员的错误码
        if (error.code === 1018001003) {
          // 显示会员引导弹窗
          uni.showModal({
            title: '会员特权',
            content: error.msg,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                // 显示VIP弹窗
                this.isVipModalVisible = true;
              }
            }
          });
        } else {
          // 其他错误显示普通提示
          uni.showToast({
            title: '重新提交失败: ' + (error.msg || error.message || '网络错误'),
            icon: 'none',
            duration: 3000
          });
        }
      }
    },

    // 处理编辑（支持联系方式和段位修改）
    async handleEdit() {
      // 检查联系方式是否填写（仅在显示联系方式字段时验证）
      if (this.shouldShowContactField) {
        if (!this.contactNumber) {
          if (this.serverType === 'wechat') {
            this.contactTip = '请填写微信号以便联系';
          } else {
            this.contactTip = '请填写QQ号以便联系';
          }
          return;
        }

        // 再次验证联系方式
        this.validateContactNumber();

        // 如果有错误提示，不提交
        if (this.contactTip) {
          uni.showToast({
            title: '请检查输入信息',
            icon: 'none'
          });
          return;
        }
      }

      // 检查是否选择了段位
      if (this.rankIndex === -1) {
        uni.showToast({
          title: '请选择段位',
          icon: 'none'
        });
        return;
      }

      // 检查是否有修改
      const currentRankLevel = this.rankOptions[this.rankIndex].value;
      const hasContactChange = this.shouldShowContactField && (this.contactNumber !== this.originalAccountData.contact);
      const hasRankChange = currentRankLevel !== this.originalAccountData.rankLevel;

      if (!hasContactChange && !hasRankChange) {
        uni.showToast({
          title: '信息未发生变化',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({
          title: '保存中...'
        });

        // 调用更新接口
        const updateData = {
          id: this.accountId,
          rankLevel: currentRankLevel,
          contact: this.shouldShowContactField ? this.contactNumber : this.originalAccountData.contact, // 根据权限控制是否更新联系方式
          remark: '通过APP编辑'
        };

        await api.game.updateGameKingAccount(updateData);

        uni.hideLoading();

        // 显示成功提示
        uni.showModal({
          title: '保存成功',
          content: '账号信息已更新',
          showCancel: false,
          success: () => {
            uni.navigateBack();
          }
        });

      } catch (error) {
        uni.hideLoading();
        console.error('保存失败:', error);
        uni.showToast({
          title: '保存失败: ' + (error.msg || error.message || '网络错误'),
          icon: 'none',
          duration: 3000
        });
      }
    },

    // 处理创建新账号
    handleCreate() {
      // 检查游戏ID是否填写
      if (!this.gameId) {
        uni.showToast({
          title: '请填写游戏ID',
          icon: 'none'
        });
        return;
      }

      // 检查是否选择了段位
      if (this.rankIndex === -1) {
        uni.showToast({
          title: '请选择段位',
          icon: 'none'
        });
        return;
      }

      // 检查联系方式是否填写（仅在显示联系方式字段时验证）
      if (this.shouldShowContactField) {
        if (!this.contactNumber) {
          if (this.serverType === 'wechat') {
            this.contactTip = '请填写微信号以便联系';
          } else {
            this.contactTip = '请填写QQ号以便联系';
          }
          return;
        }

        // 再次验证联系方式
        this.validateContactNumber();

        // 如果有错误提示，不提交
        if (this.contactTip) {
          uni.showToast({
            title: '请检查输入信息',
            icon: 'none'
          });
          return;
        }
      }

      // 检查截图是否上传
      if (!this.screenshotUrl) {
        uni.showToast({
          title: '请上传游戏主页截图',
          icon: 'none'
        });
        return;
      }

      // 检查是否正在上传图片
      if (this.isUploading) {
        uni.showToast({
          title: '图片上传中，请稍后提交',
          icon: 'none'
        });
        return;
      }

      // 检查图片是否已上传到服务器
      if (!this.serverScreenshotUrl) {
        uni.showToast({
          title: '请先上传游戏主页截图',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '提交中...'
      });

      // 使用新的游戏ID和段位
      const accountData = {
        gameId: this.gameId,
        areaType: this.serverType === 'wechat' ? 1 : 2, // 1微信区 2QQ区
        rankLevel: this.rankOptions[this.rankIndex].value, // 使用选择的段位值
        contact: this.shouldShowContactField ? this.contactNumber : '', // 根据权限控制是否传递联系方式
        screenshot: this.serverScreenshotUrl, // 使用已上传的服务器URL
        remark: '通过APP创建'
      };

      console.log('创建游戏账号:', accountData);

      // 调用接口创建账号
      api.game.createGameKingAccount(accountData).then(accountId => {
        uni.hideLoading();
        console.log('账号创建成功，ID:', accountId);

        // 显示审核等待弹窗
        this.showAuditModal(accountId);
      }).catch(err => {
        uni.hideLoading();
        console.error('创建游戏账号失败:', err);

        // 检查是否是需要开通会员的错误码
        if (err.code === 1018001004) {
          // 显示会员引导弹窗
          uni.showModal({
            title: '会员特权',
            content: err.msg,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                // 显示VIP弹窗
                this.isVipModalVisible = true;
              }
            }
          });
        } else {
          // 其他错误显示普通提示
          uni.showToast({
            title: '提交失败: ' + (err.msg || '网络错误'),
            icon: 'none',
            duration: 3000
          });
        }
      });
    },



    // 显示审核弹窗
    showAuditModal(accountId) {
      this.auditAccountId = accountId;
      this.showAuditDialog = true;
      this.auditCountdown = 30;
      this.auditStatus = 0;
      this.auditProgress = 0;
      this.auditMessage = '正在验证账号信息...';

      // 开始进度模拟
      this.startProgressSimulation();

      // 开始查询审核状态
      this.startAuditStatusCheck();
    },

    // 开始进度模拟
    startProgressSimulation() {
      this.auditTimer = setInterval(() => {
        this.auditCountdown--;

        // 模拟进度增长（非线性，开始快后面慢）
        if (this.auditProgress < 90) {
          const increment = Math.random() * 8 + 2; // 2-10的随机增长
          this.auditProgress = Math.min(90, this.auditProgress + increment);
        }

        // 30秒超时处理
        if (this.auditCountdown <= 0) {
          this.stopAuditTimers();
          this.handleAuditTimeout();
        }
      }, 1000);
    },

    // 开始查询审核状态
    startAuditStatusCheck() {
      this.auditCheckTimer = setInterval(() => {
        this.checkAuditStatus();
      }, 1000);
    },

    // 查询审核状态
    async checkAuditStatus() {
      try {
        const result = await api.game.getGameKingAccount(this.auditAccountId);
        if (result && result.auditStatus !== undefined) {
          this.auditStatus = result.auditStatus;

          if (result.auditStatus === 1) {
            // 审核通过
            this.stopAuditTimers();
            this.handleAuditSuccess();
          } else if (result.auditStatus === 2) {
            // 审核拒绝
            this.stopAuditTimers();
            this.handleAuditReject(result.rejectReason);
          }
        }
      } catch (error) {
        console.error('查询审核状态失败:', error);
      }
    },

    // 停止所有定时器
    stopAuditTimers() {
      if (this.auditTimer) {
        clearInterval(this.auditTimer);
        this.auditTimer = null;
      }
      if (this.auditCheckTimer) {
        clearInterval(this.auditCheckTimer);
        this.auditCheckTimer = null;
      }
    },

    // 审核成功
    handleAuditSuccess() {
      // 快速完成进度条
      this.auditProgress = 100;
      this.auditMessage = '验证通过！账号创建成功';

      // 播放成功特效
      this.playSuccessEffect();

      setTimeout(() => {
        this.closeAuditModal();
      }, 3000); // 延长到3秒，让用户看到特效
    },

    // 审核拒绝
    handleAuditReject(reason) {
      // 快速完成进度条
      this.auditProgress = 100;
      this.auditMessage = '昵称识别失败，请简化昵称后重试';

      // 播放失败特效
      this.playFailedEffect();
      // 不自动关闭，让用户手动关闭
    },

    // 审核超时
    handleAuditTimeout() {
      this.auditProgress = 100;
      this.auditMessage = '验证超时，请检查网络后重试';
      this.auditStatus = 2; // 设置为失败状态
      this.playFailedEffect();
      // 不自动关闭，让用户手动关闭
    },

    // 播放成功特效
    playSuccessEffect() {
      // 震动反馈
      uni.vibrateShort();

      // 可以添加音效
      // uni.playBackgroundAudio({
      //   src: '/static/sounds/success.mp3'
      // });
    },

    // 播放失败特效
    playFailedEffect() {
      // 震动反馈
      uni.vibrateLong();

      // 可以添加音效
      // uni.playBackgroundAudio({
      //   src: '/static/sounds/failed.mp3'
      // });
    },

    // 关闭审核弹窗
    closeAuditModal() {
      this.stopAuditTimers();
      this.showAuditDialog = false;
      this.auditAccountId = null;
      // 无论审核通过还是拒绝，都返回上一页
      uni.navigateBack();
    },

    // VIP购买成功回调
    onVipPurchaseSuccess(purchaseInfo) {
      console.log('VIP购买成功', purchaseInfo);
      // 关闭VIP弹窗
      this.isVipModalVisible = false;
      // 可以在这里添加购买成功后的逻辑，比如重新尝试提交
      uni.showToast({
        title: '开通成功，请重新提交',
        icon: 'success'
      });
    }
  },

  // 页面销毁时清理定时器
  beforeDestroy() {
    this.stopAuditTimers();
  },

  // uni-app 生命周期
  onUnload() {
    this.stopAuditTimers();
  }
}
</script>

<style lang="scss" scoped>
.add-account-page {
  background-color: #020303;
  min-height: 100vh;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #e0e0e0;
  position: relative;
  text-align: center;
  height: 70rpx;

  &::after {
    content: '';
    position: absolute;
    bottom: -10rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: linear-gradient(90deg, #8eac21, #B3F73C);
    border-radius: 2rpx;
  }
}

.container {
  padding: 0 30rpx 30rpx 30rpx;
}

.mode-notice {
  background: linear-gradient(135deg, rgba(255, 153, 0, 0.08) 0%, rgba(255, 153, 0, 0.12) 100%);
  border: 1rpx solid rgba(255, 153, 0, 0.2);
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 30rpx;

  // 添加微妙的阴影效果
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  .notice-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .tn-icon-warning {
      color: #FF9900;
      font-size: 36rpx;
      margin-right: 16rpx;
      // 添加微妙的发光效果
      filter: drop-shadow(0 0 4rpx rgba(255, 153, 0, 0.3));
    }

    .notice-title {
      color: #FF9900;
      font-size: 32rpx;
      font-weight: 600;
      letter-spacing: 1rpx;
    }
  }

  .notice-content {
    padding-left: 52rpx; // 与图标对齐

    text {
      display: block;
      color: rgba(255, 255, 255, 0.85);
      font-size: 28rpx;
      line-height: 1.6;
      margin-bottom: 8rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.form-box {
  background-color: #111111;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #FFFFFF;
  margin-bottom: 15rpx;
  display: flex;
  align-items: center;

  .required {
    color: #ff4d4f;
    margin-left: 5rpx;
  }

  .tip {
    font-size: 24rpx;
    color: #999999;
    margin-left: 10rpx;
  }
}

.server-selector {
  display: flex;
  justify-content: space-around;
  margin: 10rpx 0 20rpx;
}

.server-option {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #222222;
  margin: 0 10rpx;
  border-radius: 8rpx;
  color: #999999;
  font-size: 28rpx;
  transition: all 0.3s;

  &:first-child {
    margin-left: 0;
  }

  &:last-child {
    margin-right: 0;
  }

  &.active {
    background-color: rgba(179, 247, 60, 0.2);
    color: #B3F73C;
    border: 1px solid #B3F73C;
  }

  &.disabled {
    opacity: 0.6;
    cursor: not-allowed;

    &:active {
      opacity: 0.6;
    }
  }

  text {
    margin-right: 10rpx;

    &:last-child {
      margin-right: 0;
    }
  }
}

.input-wrapper {
  background-color: #222222;
  border-radius: 8rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.contact-input {
  flex: 1;
  height: 80rpx;
  color: #FFFFFF;
  font-size: 28rpx;

  &:disabled {
    color: #999999;
    background-color: transparent;
  }
}

.rank-selector {
  position: relative;
}

.picker-value {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  color: #FFFFFF;
  font-size: 28rpx;

  &.placeholder {
    color: #999999; // 未选择时使用灰色
  }

  &.disabled {
    color: #999999; // 禁用时使用灰色
  }
}

.tn-icon-arrow-down {
  color: #999999;
  font-size: 24rpx;
}

.input-tip {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #ff9800;
  margin-top: 10rpx;
  padding: 0 10rpx;
  line-height: 1.5;

  .tn-icon-info {
    margin-right: 8rpx;
    font-size: 26rpx;
  }
}

.warning-tip {
  display: flex;
  align-items: flex-start;
  font-size: 24rpx;
  color: #ff4d4f;
  margin-top: 16rpx;
  padding: 0 10rpx;
  line-height: 1.5;
  background-color: rgba(255, 77, 79, 0.1);
  border-radius: 8rpx;
  padding: 12rpx;

  .tn-icon-warning {
    margin-right: 8rpx;
    font-size: 26rpx;
    flex-shrink: 0;
    margin-top: 2rpx;
  }
}

.upload-area {
  height: 300rpx;
  background-color: #222222;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999999;

  .tn-icon-add {
    font-size: 50rpx;
    margin-bottom: 10rpx;
  }

  &.disabled {
    opacity: 0.5;
    color: #666666;
  }
}

.screenshot-preview {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 50rpx;
  height: 50rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #FFFFFF;
}

.upload-progress-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 10rpx;
  border-radius: 0 0 8rpx 8rpx;
}

.upload-progress-bar {
  height: 6rpx;
  background: linear-gradient(90deg, #8eac21, #B3F73C);
  border-radius: 3rpx;
  transition: width 0.3s ease;
  margin-bottom: 5rpx;
}

.upload-progress-text {
  font-size: 20rpx;
  color: #FFFFFF;
  text-align: center;
  line-height: 1;
}

.upload-tips {
  font-size: 24rpx;
  color: #999999;
  margin-top: 15rpx;
  line-height: 1.5;
}

.reference-images {
  display: flex;
  justify-content: center;
}

.reference-image {
  width: 100%;
  height: 400rpx;
  background-color: #222222;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
}

.reference-tip {
  font-size: 24rpx;
  color: #999999;
  line-height: 1.5;
}

.submit-btn {
  background: linear-gradient(90deg, #8eac21, #B3F73C);
  height: 90rpx;
  border-radius: 45rpx;
  color: #000000;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;

  &:disabled {
    opacity: 0.5;
  }
}

// 自定义选择器头部样式
.custom-select-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #111111;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);

  .header-cancel {
    color: #888888;
    font-size: 28rpx;
  }

  .header-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #FFFFFF;
  }

  .header-confirm {
    color: #B3F73C;
    font-size: 28rpx;
    font-weight: 500;
  }
}

/* 审核弹窗样式 */
.audit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.audit-modal {
  width: 600rpx;
  background: linear-gradient(135deg, #1a1a2e, #16213e);
  border-radius: 20rpx;
  border: 2rpx solid #B3F73C;
  box-shadow: 0 0 40rpx rgba(179, 247, 60, 0.3);
  overflow: hidden;
}

.audit-modal-bg {
  padding: 60rpx 40rpx;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="%23B3F73C" stroke-width="0.5" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
    opacity: 0.1;
    pointer-events: none;
  }
}

.audit-header {
  text-align: center;
  margin-bottom: 60rpx;
  position: relative;
  z-index: 1;
}

.audit-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #B3F73C;
  margin-bottom: 10rpx;
  text-shadow: 0 0 10rpx rgba(179, 247, 60, 0.5);
}

.audit-subtitle {
  font-size: 24rpx;
  color: #888;
}

.audit-animation {
  text-align: center;
  margin-bottom: 60rpx;
  position: relative;
  z-index: 1;
}

.audit-ring {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin: 0 auto 40rpx;
}

.ring-outer {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 4rpx solid transparent;
  border-top: 4rpx solid #B3F73C;
  border-radius: 50%;
  animation: rotate 2s linear infinite;
  transition: all 0.5s ease;

  &.success {
    border-top-color: #52c41a;
    animation: rotate 0.5s linear infinite, success-pulse 1s ease-in-out;
    box-shadow: 0 0 30rpx rgba(82, 196, 26, 0.6);
  }

  &.failed {
    border-top-color: #ff4d4f;
    animation: rotate 0.5s linear infinite, failed-shake 0.5s ease-in-out;
    box-shadow: 0 0 30rpx rgba(255, 77, 79, 0.6);
  }
}

.ring-inner {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  width: 160rpx;
  height: 160rpx;
  border: 2rpx solid transparent;
  border-bottom: 2rpx solid #8eac21;
  border-radius: 50%;
  animation: rotate-reverse 1.5s linear infinite;
  transition: all 0.5s ease;

  &.success {
    border-bottom-color: #52c41a;
    animation: rotate-reverse 0.5s linear infinite, success-pulse 1s ease-in-out;
  }

  &.failed {
    border-bottom-color: #ff4d4f;
    animation: rotate-reverse 0.5s linear infinite, failed-shake 0.5s ease-in-out;
  }
}

.ring-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #B3F73C, #8eac21);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 20rpx rgba(179, 247, 60, 0.4);
  transition: all 0.5s ease;

  &.success {
    background: linear-gradient(135deg, #52c41a, #389e0d);
    box-shadow: 0 0 30rpx rgba(82, 196, 26, 0.6);
    animation: success-bounce 0.6s ease-out;
  }

  &.failed {
    background: linear-gradient(135deg, #ff4d4f, #cf1322);
    box-shadow: 0 0 30rpx rgba(255, 77, 79, 0.6);
    animation: failed-bounce 0.6s ease-out;
  }
}

.waiting-icon {
  font-size: 40rpx;
  animation: waiting-pulse 2s ease-in-out infinite;
}

.success-icon {
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
  animation: success-scale 0.6s ease-out;
}

.failed-icon {
  font-size: 48rpx;
  font-weight: bold;
  color: #fff;
  animation: failed-scale 0.6s ease-out;
}

.audit-status {
  font-size: 28rpx;
  color: #fff;
  margin-bottom: 30rpx;
  transition: all 0.3s ease;

  &.success {
    color: #52c41a;
    font-weight: bold;
    animation: success-text-glow 1s ease-in-out;
  }

  &.failed {
    color: #ff4d4f;
    font-weight: bold;
    animation: failed-text-glow 1s ease-in-out;
  }
}

.audit-progress {
  width: 100%;
  margin-bottom: 20rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #8eac21, #B3F73C);
  border-radius: 4rpx;
  transition: width 0.3s ease;

  &.success {
    background: linear-gradient(90deg, #389e0d, #52c41a);
    box-shadow: 0 0 10rpx rgba(82, 196, 26, 0.5);
    animation: success-progress-glow 1s ease-in-out;
  }

  &.failed {
    background: linear-gradient(90deg, #cf1322, #ff4d4f);
    box-shadow: 0 0 10rpx rgba(255, 77, 79, 0.5);
    animation: failed-progress-glow 1s ease-in-out;
  }
}

.audit-footer {
  text-align: center;
  position: relative;
  z-index: 1;
}

.audit-btn {
  background: linear-gradient(90deg, #8eac21, #B3F73C);
  color: #000;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 15rpx rgba(179, 247, 60, 0.3);

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 10rpx rgba(179, 247, 60, 0.3);
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes rotate-reverse {
  from { transform: rotate(360deg); }
  to { transform: rotate(0deg); }
}

@keyframes waiting-pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.7; transform: scale(1.1); }
}

@keyframes success-pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

@keyframes failed-shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5rpx); }
  75% { transform: translateX(5rpx); }
}

@keyframes success-bounce {
  0% { transform: translate(-50%, -50%) scale(1); }
  50% { transform: translate(-50%, -50%) scale(1.2); }
  100% { transform: translate(-50%, -50%) scale(1); }
}

@keyframes failed-bounce {
  0% { transform: translate(-50%, -50%) scale(1); }
  25% { transform: translate(-50%, -50%) scale(0.9); }
  50% { transform: translate(-50%, -50%) scale(1.1); }
  100% { transform: translate(-50%, -50%) scale(1); }
}

@keyframes success-scale {
  0% { transform: scale(0); opacity: 0; }
  50% { transform: scale(1.3); opacity: 1; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes failed-scale {
  0% { transform: scale(0); opacity: 0; }
  50% { transform: scale(1.3); opacity: 1; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes success-text-glow {
  0%, 100% { text-shadow: 0 0 5rpx rgba(82, 196, 26, 0.5); }
  50% { text-shadow: 0 0 15rpx rgba(82, 196, 26, 0.8); }
}

@keyframes failed-text-glow {
  0%, 100% { text-shadow: 0 0 5rpx rgba(255, 77, 79, 0.5); }
  50% { text-shadow: 0 0 15rpx rgba(255, 77, 79, 0.8); }
}

@keyframes success-progress-glow {
  0%, 100% { box-shadow: 0 0 10rpx rgba(82, 196, 26, 0.5); }
  50% { box-shadow: 0 0 20rpx rgba(82, 196, 26, 0.8); }
}

@keyframes failed-progress-glow {
  0%, 100% { box-shadow: 0 0 10rpx rgba(255, 77, 79, 0.5); }
  50% { box-shadow: 0 0 20rpx rgba(255, 77, 79, 0.8); }
}
</style>
